package swta.crud.snippet

import net.liftweb.http.S
import net.liftweb.http.SHtml._
import net.liftweb.util.Helpers._
import scala.xml.NodeSeq
import scala.xml.Node
import scala.xml.Group
import scala.xml.Text
import net.liftweb.util.Full
import net.liftweb.util.Empty

import swta.crud.model.Item
import swta.crud.model.Bundle
import swta.crud.model.BundleItem

class BundleManager {

    def addBundle(xhtml: Group): NodeSeq = {
    val form = (new Bundle).toForm(
      Full("Post"),
      bundle => {
        bundle.save
        
        /*
         * The key matching the SELECT-id contains List(2, 1, 4) as a value.
         */

        val params = S.request.open_!.params
//        println(params.keys.foldLeft(""){(str, key) => str + " ### " + key.toString})
//        println(params.values.foldLeft(""){(str, key) => str + " ### " + key.toString})
//        println("*****   params.toString:   " + params.toString)
        
        val amounts = params.get("txtAmount").get
        var i = 0

        params.get("selItems").get.foreach(itemId => {
          val bi = BundleItem.create

          /* Ohne .is gibt's die merkwuerdige "malformed Scala signature"
           * Fehlermeldung beim Compilieren mit scala:cc.
           */
          bi.bundleId.set(bundle.id.is)
          bi.itemId.set(itemId.toLong)
          bi.amount.set(amounts(i).toInt)

          bi.save
          
//          println("*****   Whatsoeverly created BundleItem:   " + bi)
//          println()

          i = i + 1
        })

        S.redirectTo("list")
      })
    
    /* @note Look up SELECT's generated name via select(...).attribute("name") 
     *		 instead of overwriting it with a static one. 
     */

    val itemSelector = bind("item", xhtml,
      "items" -> select(Item.findAll.map(s => (s.id.toString, s.name)), Empty, choice => println("*****   SELECT_CALLBACK: " + choice)) % ("name" -> "selItems"),
      "amount" -> text("1", choice => println("*****   TEXT_CALLBACK: " + choice)) % ("name" -> "txtAmount")
    )
    
    return form.take(2) ++ itemSelector ++  form.drop(2)
  }

  def viewBundles(xhtml: Group): NodeSeq = {
    val bundles = Bundle.findAll
    
    bundles match {
      case Nil => <div>No bundles existing.</div>
      
      case bundles => bundles.flatMap(
        bundle => bind("bundle", xhtml,
          "name" -> bundle.name,
          "description" -> bundle.description,
          "discount" -> bundle.discount,
          "price" -> "47.11",
          "items" -> bundle.items.toString)
      )
    }
  }
}
